﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;

namespace YunShop_WebAPI.BLL
{
    /// <summary>
    /// 通用帮助类
    /// </summary>
    public static class CommonHelper
    {




        #region 判断字符串是否为手机号码
        /// <summary>
        /// 判断字符串是否为手机号码
        /// </summary>
        /// <param name="mobilePhoneNumber"></param>
        /// <returns></returns>
        public static bool IsMobile(string mobilePhoneNumber)
        {
            if (mobilePhoneNumber.Length < 11)
            {
                return false;
            }

            string mobile = @"^1[3456789][0123456789]\d{8}$";
            Regex regexMobile = new Regex(mobile);
            if (regexMobile.IsMatch(mobilePhoneNumber))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 检测是否符合email格式

        /// <summary>
        ///     检测是否符合email格式
        /// </summary>
        /// <param name="strEmail">要判断的email字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsValidEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]");
        }

        public static bool IsValidDoEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail,
                @"^@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
        #endregion

        #region 检测是否是正确的Url
        /// <summary>
        ///     检测是否是正确的Url
        /// </summary>
        /// <param name="strUrl">要验证的Url</param>
        /// <returns>判断结果</returns>
        public static bool IsUrl(string strUrl)
        {
            return Regex.IsMatch(strUrl,
                @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
        }


        #endregion

        #region string 转int数组

        public static int[] StringToIntArray(string str)
        {
            try
            {
                if (string.IsNullOrEmpty(str)) return new int[0];
                if (str.EndsWith(","))
                {
                    str = str.Remove(str.Length - 1, 1);
                }
                var idstrarr = str.Split(',');
                var idintarr = new int[idstrarr.Length];

                for (int i = 0; i < idstrarr.Length; i++)
                {
                    idintarr[i] = Convert.ToInt32(idstrarr[i]);
                }
                return idintarr;
            }
            catch
            {
                return new int[0];
            }
        }
        #endregion

        #region String转数组
        public static string[] StringToStringArray(string str)
        {
            try
            {
                if (string.IsNullOrEmpty(str)) return new string[0];
                if (str.EndsWith(",")) str = str.Remove(str.Length - 1, 1);
                return str.Split(',');
            }
            catch
            {
                return new string[0];
            }
        }
        #endregion

        #region String数组转Int数组
        public static int[] StringArrAyToIntArray(string[] str)
        {
            try
            {
                int[] iNums = Array.ConvertAll<string, int>(str, s => int.Parse(s));
                return iNums;
            }
            catch
            {
                return new int[0];
            }
        }
        #endregion

        #region string转Guid数组
        public static System.Guid[] StringToGuidArray(string str)
        {
            try
            {
                if (string.IsNullOrEmpty(str)) return new System.Guid[0];
                if (str.EndsWith(",")) str = str.Remove(str.Length - 1, 1);
                var strarr = str.Split(',');
                System.Guid[] guids = new System.Guid[strarr.Length];
                for (int index = 0; index < strarr.Length; index++)
                {
                    guids[index] = System.Guid.Parse(strarr[index]);
                }
                return guids;
            }
            catch
            {
                return new System.Guid[0];
            }
        }
        #endregion

        #region String转long
        public static long[] StringToLongArray(string str)
        {
            try
            {
                if (string.IsNullOrEmpty(str)) return new long[0];
                if (str.EndsWith(","))
                {
                    str = str.Remove(str.Length - 1, 1);
                }
                var idstrarr = str.Split(',');
                var idlongarr = new long[idstrarr.Length];

                for (int i = 0; i < idstrarr.Length; i++)
                {
                    idlongarr[i] = Convert.ToInt64(idstrarr[i]);
                }
                return idlongarr;
            }
            catch
            {
                return new long[0];
            }
        }
        #endregion

        #region 转MD5
        /// <summary>
        /// 转MD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToMd5(string str)
        {
            MD5 md5 = MD5.Create();
            // 将字符串转换成字节数组
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // 调用加密方法
            byte[] byteNew = md5.ComputeHash(byteOld);
            // 将加密结果转换为字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // 将字节转换成16进制表示的字符串，
                sb.Append(b.ToString("x2"));
            }
            // 返回加密的字符串
            return sb.ToString();
        }
        #endregion

        #region 获取32位md5加密
        /// <summary>
        /// 通过创建哈希字符串适用于任何 MD5 哈希函数 （在任何平台） 上创建 32 个字符的十六进制格式哈希字符串
        /// </summary>
        /// <param name="source"></param>
        /// <returns>32位md5加密字符串</returns>
        public static string Md5For32(string source)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source));
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                string hash = sBuilder.ToString();
                return hash.ToUpper();
            }
        }
        #endregion

        #region 获取16位md5加密
        /// <summary>
        /// 获取16位md5加密
        /// </summary>
        /// <param name="source"></param>
        /// <returns>16位md5加密字符串</returns>
        public static string Md5For16(string source)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source));
                //转换成字符串，并取9到25位
                string sBuilder = BitConverter.ToString(data, 4, 8);
                //BitConverter转换出来的字符串会在每个字符中间产生一个分隔符，需要去除掉
                sBuilder = sBuilder.Replace("-", "");
                return sBuilder.ToUpper();
            }
        }

        #endregion

        #region 返回当前的毫秒时间戳

        /// <summary>
        /// 返回当前的毫秒时间戳
        /// </summary>
        public static string Msectime()
        {
            long timeTicks = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
            return timeTicks.ToString();
        }


        #endregion


        #region 剩余多久时间文字描述
        /// <summary>
        /// 剩余多久时间
        /// </summary>
        /// <param name="remainingTime"></param>
        /// <returns>文字描述</returns>
        public static string GetRemainingTime(DateTime remainingTime)
        {
            TimeSpan timeSpan = remainingTime - DateTime.Now;
            var day = timeSpan.Days;
            var hours = timeSpan.Hours;
            var minute = timeSpan.Minutes;
            var seconds = timeSpan.Seconds;
            if (day > 0)
            {
                return day + "天" + hours + "小时" + minute + "分" + seconds + "秒";
            }
            else
            {
                if (hours > 0)
                {
                    return hours + "小时" + minute + "分" + seconds + "秒";
                }
                else
                {
                    return minute + "分" + seconds + "秒";
                }
            }
        }

        #endregion

        #region 剩余多久时间返回时间类型
        /// <summary>
        /// 剩余多久时间
        /// </summary>
        /// <param name="remainingTime"></param>
        /// <returns>返回时间类型</returns>
        public static void GetBackTime(DateTime remainingTime, out int day, out int hours, out int minute, out int seconds)
        {
            TimeSpan timeSpan = remainingTime - DateTime.Now;
            day = timeSpan.Days;
            hours = timeSpan.Hours;
            minute = timeSpan.Minutes;
            seconds = timeSpan.Seconds;
        }

        #endregion

        #region 计算时间戳剩余多久时间

        /// <summary>
        /// 计算时间戳剩余多久时间
        /// </summary>
        /// <param name="postTime">提交时间(要是以前的时间)</param>
        /// <returns></returns>
        public static string TimeAgo(DateTime postTime)
        {
            //当前时间的时间戳
            var nowtimes = ConvertTicks(DateTime.Now);
            //提交的时间戳
            var posttimes = ConvertTicks(postTime);
            //相差时间戳
            var counttime = nowtimes - posttimes;

            //进行时间转换
            if (counttime <= 60)
            {
                return "刚刚";
            }
            else if (counttime > 60 && counttime <= 120)
            {
                return "1分钟前";
            }
            else if (counttime > 120 && counttime <= 180)
            {
                return "2分钟前";
            }
            else if (counttime > 180 && counttime < 3600)
            {
                return Convert.ToInt32((counttime / 60)) + "分钟前";
            }
            else if (counttime >= 3600 && counttime < 3600 * 24)
            {
                return Convert.ToInt32((counttime / 3600)) + "小时前";
            }
            else if (counttime >= 3600 * 24 && counttime < 3600 * 24 * 2)
            {
                return "昨天";
            }
            else if (counttime >= 3600 * 24 * 2 && counttime < 3600 * 24 * 3)
            {
                return "前天";
            }
            else if (counttime >= 3600 * 24 * 3 && counttime <= 3600 * 24 * 7)
            {
                return Convert.ToInt32((counttime / (3600 * 24))) + "天前";
            }
            else if (counttime >= 3600 * 24 * 7 && counttime <= 3600 * 24 * 30)
            {
                return Convert.ToInt32((counttime / (3600 * 24 * 7))) + "周前";
            }
            else if (counttime >= 3600 * 24 * 30 && counttime <= 3600 * 24 * 365)
            {
                return Convert.ToInt32((counttime / (3600 * 24 * 30))) + "个月前";
            }
            else if (counttime >= 3600 * 24 * 365)
            {
                return Convert.ToInt32((counttime / (3600 * 24 * 365))) + "年前";
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 时间转换为秒的时间戳
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private static long ConvertTicks(DateTime time)
        {
            long currentTicks = time.Ticks;
            DateTime dtFrom = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            long currentMillis = (currentTicks - dtFrom.Ticks) / 10000000;  //转换为秒为Ticks/10000000，转换为毫秒Ticks/10000
            return currentMillis;
        }

        #endregion

        #region 清除HTML中指定样式
        /// <summary>
        /// 清除HTML中指定样式
        /// </summary>
        /// <param name="content"></param>
        /// <param name="rule"></param>
        /// <returns></returns>
        public static string ClearHtml(string content, string[] rule)
        {
            if (!rule.Any())
            {
                return content;
            }

            foreach (var item in rule)
            {
                content = Regex.Replace(content, "/" + item + @"\s*=\s*\d+\s*/i", "");
                content = Regex.Replace(content, "/" + item + @"\s*=\s*.+?[""]/i", "");
                content = Regex.Replace(content, "/" + item + @"\s*:\s*\d+\s*px\s*;?/i", "");
            }
            return content;
        }
        #endregion

        #region list随机排序方法
        /// <summary>
        /// list随机排序方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ListT"></param>
        /// <returns></returns>
        public static List<T> RandomSortList<T>(List<T> ListT)
        {
            Random random = new Random();
            List<T> newList = new List<T>();
            foreach (T item in ListT)
            {
                newList.Insert(random.Next(newList.Count + 1), item);
            }
            return newList;
        }
        #endregion





        #region 截前后字符(串)
        ///<summary>
        /// 截前后字符(串)
        ///</summary>
        ///<param name="val">原字符串</param>
        ///<param name="str">要截掉的字符串</param>
        ///<param name="all">是否贪婪</param>
        ///<returns></returns>
        public static string GetCaptureInterceptedText(string val, string str, bool all = false)
        {
            return Regex.Replace(val, @"(^(" + str + ")" + (all ? "*" : "") + "|(" + str + ")" + (all ? "*" : "") + "$)", "");
        }
        #endregion

        #region 密码加密方法
        /// <summary>
        /// 密码加密方法
        /// </summary>
        /// <param name="password">要加密的字符串</param>
        /// <param name="createTime">时间组合</param>
        /// <returns></returns>
        public static string EnPassword(string password, DateTime createTime)
        {
            var dtStr = createTime.ToString("yyyyMMddHHmmss");
            var md5 = Md5For32(password);
            var enPwd = Md5For32(md5 + dtStr);
            return enPwd;
        }
        #endregion

        #region 获取现在是星期几
        /// <summary>
        /// 获取现在是星期几
        /// </summary>
        /// <returns></returns>
        public static string GetWeek()
        {
            string week = string.Empty;
            switch (DateTime.Now.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    week = "周一";
                    break;
                case DayOfWeek.Tuesday:
                    week = "周二";
                    break;
                case DayOfWeek.Wednesday:
                    week = "周三";
                    break;
                case DayOfWeek.Thursday:
                    week = "周四";
                    break;
                case DayOfWeek.Friday:
                    week = "周五";
                    break;
                case DayOfWeek.Saturday:
                    week = "周六";
                    break;
                case DayOfWeek.Sunday:
                    week = "周日";
                    break;
                default:
                    week = "N/A";
                    break;
            }
            return week;
        }

        #endregion

        #region UrlEncode (URL编码)
        /// <summary>
        /// UrlEncode (URL编码)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }

            return (sb.ToString());
        }

        #endregion

        #region 获取10位时间戳
        /// <summary>
        /// 获取10位时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetTimeStampByTotalSeconds()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }
        #endregion

        #region 获取13位时间戳
        /// <summary>
        /// 获取13位时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetTimeStampByTotalMilliseconds()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds);
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static int GetDateTimeStamp(DateTime dt)
        {
            DateTime dateStart = new DateTime(1970, 1, 1, 0, 0, 0);
            int timeStamp = Convert.ToInt32((dt.ToUniversalTime() - dateStart).TotalSeconds);
            return timeStamp;
        }

        #endregion

        #region 获取随机字符串
        /// <summary>
        /// 获取随机字符串
        /// </summary>
        /// <returns></returns>
        public static string GetSerialNumber()
        {
            var str = string.Empty;
            Random rand = new Random();
            var charsStr2 = new[] { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
            var charsLen2 = charsStr2.Length - 1;
            //    shuffle($chars);
            str = "";
            for (int i = 0; i < 16; i++)
            {
                str += charsStr2[rand.Next(0, charsLen2)];
            }
            return str;
        }

        #endregion

        #region Sha1签名
        /// <summary>
        /// Sha1签名
        /// </summary>
        /// <param name="str">内容</param>
        /// <param name="encoding">编码</param>
        /// <returns></returns>
        public static string Sha1Signature(string str, Encoding encoding = null)
        {
            if (encoding == null) encoding = Encoding.UTF8;
            var buffer = encoding.GetBytes(str);
            var data = SHA1.Create().ComputeHash(buffer);
            StringBuilder sub = new StringBuilder();
            foreach (var t in data)
            {
                sub.Append(t.ToString("x2"));
            }

            return sub.ToString();
        }
        #endregion




        #region 获取配置文件
        /// <summary>
        /// 配置文件获取
        /// </summary>
        /// <returns></returns>
        public static string GetConnectionString()
        {
            // 读取配置文件内容
            string configText = File.ReadAllText("appsettings.json");

            // 解析为JSON对象
            JObject configJson = JObject.Parse(configText);

            // 获取SqlConnection字段值
            string sqlConnection = configJson["ConnectionStrings"]["SqlConnection"].ToString();

            return sqlConnection;
        }
        #endregion

        #region 集合转string

        public static string GetFeedTastIds(ArrayList list)
        {
            list.Sort();
            string idsStr = "";
            for (int i = 0; i < list.Count; i++)
            {
                if (!string.IsNullOrEmpty(idsStr)) idsStr = idsStr + "-";
                idsStr = idsStr + ConvertToString(list[i]);
            }
            return idsStr;
        }

        public static string ConvertToString(Object obj)
        {
            try
            {
                if (obj == null)
                {
                    return "";
                }
                if (obj == DBNull.Value)
                {
                    return "";
                }
                return Convert.ToString(obj);
            }
            catch (Exception E)
            {
                return "";
            }
        }
        #endregion

        #region 生成6位数字随机数
        public static string GetRomNum(int length = 6)
        {
            Random random = new Random();
            int randomNumber = random.Next(1, 10) * 100000 + random.Next(0, 100000);
            return randomNumber.ToString("D6");
        }
        #endregion


        /// <summary>
        /// 包含大小写数字的随机字符串
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static string GenerateSecureString(int length)
        {
            const string upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            const string lowerChars = "abcdefghijklmnopqrstuvwxyz";
            const string digits = "0123456789";

            Random random = new Random();
            StringBuilder builder = new StringBuilder();

            // 添加一个大写字母  
            builder.Append(upperChars[random.Next(upperChars.Length)]);

            // 添加一个小写字母  
            builder.Append(lowerChars[random.Next(lowerChars.Length)]);

            // 添加一个数字  
            builder.Append(digits[random.Next(digits.Length)]);

            // 填充剩余位置，可以是任意字符  
            const string allChars = upperChars + lowerChars + digits;
            for (int i = 3; i < length; i++)
            {
                builder.Append(allChars[random.Next(allChars.Length)]);
            }

            // 打乱字符串顺序以确保随机性  
            char[] charArray = builder.ToString().ToCharArray();
            for (int i = charArray.Length - 1; i > 0; i--)
            {
                int n = random.Next(i + 1);
                char temp = charArray[i];
                charArray[i] = charArray[n];
                charArray[n] = temp;
            }

            return new string(charArray);
        }


        /// <summary>
        /// 创建验证码随机内容
        /// </summary>
        /// <param name="vcodeNum"></param>
        /// <returns></returns>
        private static string RndImgCode(int vcodeNum)
        {
            //验证码可以显示的字符集合  
            //string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p" +
            //    ",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q" +
            //    ",R,S,T,U,V,W,X,Y,Z";
            string Vchar = "0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,6,8";
            string[] VcArray = Vchar.Split(new Char[] { ',' });//拆分成数组   
            string code = "";//产生的随机数  
            int temp = -1;//记录上次随机数值，尽量避避免生产几个一样的随机数  

            Random rand = new Random();
            //采用一个简单的算法以保证生成随机数的不同  
            for (int i = 1; i < vcodeNum + 1; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));//初始化随机类  
                }
                int t = rand.Next(61);//获取随机数  
                if (temp != -1 && temp == t)
                {
                    return RndImgCode(vcodeNum);//如果获取的随机数重复，则递归调用  
                }
                temp = t;//把本次产生的随机数记录起来  
                code += VcArray[t];//随机数的位数加一  
            }
            return code;
        }

        /// <summary>
        /// 创建动态验证码图片
        /// </summary>
        /// <param name="code"></param>
        /// <param name="savePath"></param>
        /// <param name="numbers"></param>
        /// <returns></returns>
        public static MemoryStream CreateImgVerifyCode(out string code, string savePath, int numbers = 4)
        {
            code = RndImgCode(numbers);
            //Bitmap img = null;
            //Graphics g = null;
            MemoryStream ms = null;
            Random random = new Random();
            //验证码颜色集合  
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            //验证码字体集合
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };


            using (var img = new Bitmap((int)code.Length * 18, 32))
            {
                using (var g = Graphics.FromImage(img))
                {
                    g.Clear(Color.White);//背景设为白色

                    //在随机位置画背景点  
                    for (int i = 0; i < 100; i++)
                    {
                        int x = random.Next(img.Width);
                        int y = random.Next(img.Height);
                        g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
                    }
                    //验证码绘制在g中  
                    for (int i = 0; i < code.Length; i++)
                    {
                        int cindex = random.Next(7);//随机颜色索引值  
                        int findex = random.Next(5);//随机字体索引值  
                        Font f = new Font(fonts[findex], 15, FontStyle.Bold);//字体  
                        Brush b = new SolidBrush(c[cindex]);//颜色  
                        int ii = 4;
                        if ((i + 1) % 2 == 0)//控制验证码不在同一高度  
                        {
                            ii = 2;
                        }
                        g.DrawString(code.Substring(i, 1), f, b, 3 + (i * 12), ii);//绘制一个验证字符  
                    }
                    //ms = new MemoryStream();//生成内存流对象  
                    img.Save(savePath);
                }
            }
            return ms;
        }


        /// <summary>
        /// 创建SecretKey
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GenerateSecureRandomString(int length = 32)
        {
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                StringBuilder result = new StringBuilder();
                while (result.Length < length)
                {
                    byte[] oneByte = new byte[1];
                    rng.GetBytes(oneByte);
                    char character = (char)oneByte[0];

                    // 只选择可打印的ASCII字符  
                    if ((character >= '0' && character <= '9') ||
                        (character >= 'a' && character <= 'z') ||
                        (character >= 'A' && character <= 'Z'))
                    //character == '-' || character == '_' || character == '.')  
                    {
                        result.Append(character);
                    }
                }
                return result.ToString();
            }
        }


        /// <summary>
        /// 获取单据编码
        /// </summary>
        public static long GetCorpNextId(int storeId, long NextId)
        {
            string strFirst = storeId.ToString();
            int countLast = 18 - strFirst.Length;
            string strLast = NextId.ToString().PadLeft(countLast, '0').PadRight(countLast);
            string str = strFirst + strLast;
            long orderId = Convert.ToInt64(str);
            if (orderId.ToString().Length < 10) orderId = NextId;
            return orderId;
        }


        /// <summary>
        /// http 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public async static Task<string> HttpPost(string url, dynamic body)
        {
            string result = string.Empty;
            //设置Http的正文
            HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(body));
            //设置Http的内容标头
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            //设置Http的内容标头的字符
            httpContent.Headers.ContentType.CharSet = "utf-8";
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(10); ;
                    //异步Post
                    HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
                    return await response.Content.ReadAsStringAsync();
                }
            }
            catch (Exception ex)
            {
                //object data = new
                //{
                //    code = 1,
                //    msg = ex.Message,
                //};
                //return JsonConvert.SerializeObject(data);
                return null;
            }
        }





        public static void CreateThumbnail(string originalImagePath, string thumbnailPath, int thumbnailWidth = 170, int thumbnailHeight = 170)
        {
            // 加载原始图片
            using (Image originalImage = Image.FromFile(originalImagePath))
            {
                // 计算缩放比例
                float ratio = Math.Min((float)thumbnailWidth / originalImage.Width, (float)thumbnailHeight / originalImage.Height);
                int width = (int)(originalImage.Width * ratio);
                int height = (int)(originalImage.Height * ratio);

                // 创建缩略图的大小
                Size thumbnailSize = new Size(width, height);

                // 新建一个bmp图片
                using (Image thumbnailImage = new Bitmap(thumbnailWidth, thumbnailHeight))
                {
                    using (Graphics graphics = Graphics.FromImage(thumbnailImage))
                    {
                        // 设置高质量插值法
                        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        // 设置高质量,低速度绘图
                        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        // 清除旧的背景色
                        graphics.Clear(Color.Transparent);
                        // 绘制缩略图
                        graphics.DrawImage(originalImage, new Rectangle((thumbnailWidth - width) / 2, (thumbnailHeight - height) / 2, width, height),
                                            new Rectangle(0, 0, originalImage.Width, originalImage.Height),
                                            GraphicsUnit.Pixel);

                        // 保存缩略图
                        thumbnailImage.Save(thumbnailPath, originalImage.RawFormat);
                    }
                }
            }
        }



    }



}
